<?php

$guid = $path[3];

if ($guid) {
	
	$template = $db->fetchRow("SELECT * FROM cms_email_templates WHERE site_id=? AND guid=?", array($site['id'], $guid));
	
	if (!$template) {
		$db->insert('cms_email_templates', array(
			'guid' => $guid,
			'site_id' => $site['id']
		));
		$template = $db->fetchRow("SELECT * FROM cms_email_templates WHERE site_id=? AND guid=?", array($site['id'], $guid));
	}
	
	if ($_POST) {
		if ($_POST['template']) {
			$db->update('cms_email_templates', $_POST['template'], $db->quoteInto("guid=?", $guid) . ' AND ' . $db->quoteInto("site_id=?", $site['id']));
			$smarty->assign('success', true);
		} else{
			$smarty->assign('errors', array('FILENAME'));
		}
	}
	
	$smarty->assign('template', $template);
	
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		header('Content-type: text/xml');
		$smarty->display('global/email-templates/_edit_messages.tpl.taconite');
	} else {
		$smarty->display('global/email-templates/edit.tpl.html');
	}
	
} else {
	header("Location: /admin/global/email-templates/");
}